<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta name="baidu-site-verification" content="code-Vc9hmj7JE9" />
<meta name="google-site-verification" content="tMVEtTlHbEdIEga44DZi47Yu8Pl2shFKVZcqz6rfSW0" />
<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://kun-bin.github.io/");
                } else {
                    history.back();
                }
            }
        }
    })();
</script>








<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="/css/matery.css">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="python," />










<meta name="description" content="实际上在这之前还有两课讲scikit库，不过没作业，就不整理内容了。">
<meta property="og:type" content="article">
<meta property="og:title" content="python课程期末作业">
<meta property="og:url" content="https://likun1208.github.io/2020/06/13/python%E8%AF%BE%E7%A8%8B%E6%9C%9F%E6%9C%AB%E4%BD%9C%E4%B8%9A/index.html">
<meta property="og:site_name" content="左边">
<meta property="og:description" content="实际上在这之前还有两课讲scikit库，不过没作业，就不整理内容了。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-06-13T07:20:05.000Z">
<meta property="article:modified_time" content="2020-12-21T06:31:24.687Z">
<meta property="article:author" content="Kun Li">
<meta property="article:tag" content="python">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://likun1208.github.io/2020/06/13/python课程期末作业/"/>





  <title>python课程期末作业 | 左边</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">左边</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>
	<script type="text/javascript" src="/js/echarts.min.js"></script>
    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://likun1208.github.io/2020/06/13/python%E8%AF%BE%E7%A8%8B%E6%9C%9F%E6%9C%AB%E4%BD%9C%E4%B8%9A/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Kun Li">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="左边">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python课程期末作业</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-06-13T15:20:05+08:00">
                2020-06-13
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index">
                    <span itemprop="name">课程笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>实际上在这之前还有两课讲<code>scikit</code>库，不过没作业，就不整理内容了。</p>
<a id="more"></a>
<h1 align = "center">北京师范大学2019～2020学年第二学期期末大作业</h1>
<h1 align = "center">（研究生）</h1>

<p><strong>课程名称：</strong><u>Python编程之美</u>   &nbsp;&emsp;&emsp;&emsp; <strong>任课教师姓名：</strong><u>邓擎琼</u></p>
<p><strong>总分</strong>：<u>40</u>   </p>
<p><strong>院 系：</strong><u>人工智能学院</u> &nbsp;&emsp;&emsp;&emsp; <strong>年级：</strong><u>2019级</u></p>
<p><strong>姓 名：</strong><u>李琨</u>   &nbsp;&emsp;&emsp;&emsp; <strong>学 号：</strong><u>201931210003</u></p>
<div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:left">题号</th>
<th style="text-align:center">第一题</th>
<th style="text-align:center">第二题</th>
<th style="text-align:center">第三题</th>
<th style="text-align:center">第四题</th>
<th style="text-align:center">第五题</th>
<th style="text-align:right">总分</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">得分</td>
<td style="text-align:center"></td>
<td style="text-align:center"></td>
<td style="text-align:center"></td>
<td style="text-align:center"></td>
<td style="text-align:center"></td>
</tr>
</tbody>
</table>
</div>
<p><strong>阅卷教师（签字）：</strong><u> &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;</u></p>
<h2 id="题目："><a href="#题目：" class="headerlink" title="题目："></a>题目：</h2><ol>
<li>读入北京历史天气数据（北京天气.xlsx）；  <font color='red'>分值：3</font><br>或者：从<a href="http://www.tianqihoubao.com/lishi/beijing.html" target="_blank" rel="noopener">http://www.tianqihoubao.com/lishi/beijing.html</a><br>网站上通过爬虫把北京2011年-至今的天气数据爬下来，并保存为Excel文件；  <font color='red'>分值：10</font></li>
<li>读入北京空气质量数据（北京空气质量.xlsx），并把该数据和第1步中得到的北京天气数据进行融合，得到一个同时包含天气和空气质量的表格数据，保存为Excel文件；   <font color='red'>分值：5</font></li>
<li>对2011-2019年的每一年，统计这一年中白天为晴、雨、多云、阴、雪、雾霾、扬沙的天数，并绘制成饼图；    <font color='red'>分值：4</font></li>
<li>对2014-2019年的每一年，统计这一年中持续1天污染的次数、持续2天污染的次数、持续3天污染的次数、持续4天污染的次数和持续5天及以上有污染的次数，把所有年份的统计结果绘制成一幅柱状图；    <font color='red'>分值：6</font></li>
<li>在北京历史天气和空气质量数据的基础上，根据当天的天气情况以及前两天的天气及空气质量情况，预测当天的空气质量等级，要求至少比较两种算法，从中选出较优的算法并确定最优超参数（如果算法有超参数的话） 。  <font color='red'>分值：15</font></li>
</ol>
<h2 id="承诺："><a href="#承诺：" class="headerlink" title="承诺："></a>承诺：</h2><p>本人承诺本程序是自己编写的，没有抄袭。</p>
<h3 id="导入库"><a href="#导入库" class="headerlink" title="导入库"></a>导入库</h3><p>首先列出所有用到的库，如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">import</span> csv</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">from</span> bs4 <span class="keyword">import</span> BeautifulSoup</span><br><span class="line"><span class="keyword">from</span> requests.compat <span class="keyword">import</span> urljoin</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">from</span> sklearn.feature_extraction <span class="keyword">import</span> DictVectorizer</span><br><span class="line"><span class="keyword">from</span> sklearn.feature_extraction.text <span class="keyword">import</span> CountVectorizer</span><br><span class="line"><span class="keyword">from</span> sklearn.preprocessing <span class="keyword">import</span> PolynomialFeatures, StandardScaler</span><br><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> Counter</span><br><span class="line"><span class="keyword">from</span> sklearn.model_selection <span class="keyword">import</span> train_test_split</span><br><span class="line"><span class="keyword">from</span> sklearn.model_selection <span class="keyword">import</span> cross_val_score</span><br><span class="line"><span class="keyword">from</span> sklearn.model_selection <span class="keyword">import</span> StratifiedKFold</span><br><span class="line"><span class="keyword">from</span> sklearn.metrics <span class="keyword">import</span> classification_report</span><br><span class="line"><span class="keyword">from</span> sklearn.metrics <span class="keyword">import</span> confusion_matrix</span><br><span class="line"><span class="keyword">from</span> sklearn.metrics <span class="keyword">import</span> accuracy_score</span><br><span class="line"><span class="keyword">from</span> sklearn.linear_model <span class="keyword">import</span> LogisticRegression</span><br><span class="line"><span class="keyword">from</span> sklearn.tree <span class="keyword">import</span> DecisionTreeClassifier</span><br><span class="line"><span class="keyword">from</span> sklearn.neighbors <span class="keyword">import</span> KNeighborsClassifier</span><br><span class="line"><span class="keyword">from</span> sklearn.discriminant_analysis <span class="keyword">import</span> LinearDiscriminantAnalysis</span><br><span class="line"><span class="keyword">from</span> sklearn.naive_bayes <span class="keyword">import</span> GaussianNB</span><br><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> svm</span><br><span class="line"><span class="keyword">from</span> sklearn.svm <span class="keyword">import</span> SVC</span><br><span class="line"><span class="keyword">from</span> sklearn.svm <span class="keyword">import</span> LinearSVC</span><br><span class="line"><span class="keyword">from</span> sklearn.pipeline <span class="keyword">import</span> Pipeline</span><br><span class="line"><span class="keyword">from</span> sklearn.preprocessing <span class="keyword">import</span> OrdinalEncoder, OneHotEncoder, LabelEncoder</span><br></pre></td></tr></table></figure>
<ol>
<li>考虑到题目中有画图的要求，而内容有中文，因此先将<code>plt</code>的字体改为中文字体。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">plt.rcParams[<span class="string">'font.sans-serif'</span>] = [<span class="string">'SimHei'</span>]</span><br></pre></td></tr></table></figure>
<h3 id="第一题"><a href="#第一题" class="headerlink" title="第一题"></a>第一题</h3><ol>
<li><p>首先分析天气数据的<a href="http://www.tianqihoubao.com/lishi/beijing.html" target="_blank" rel="noopener">网页链接</a>，该页面并不直接包含天气数据，而是包含了指向每个月天气数据的链接，因此需要先从该页面把所有月份的链接提取出来。经过分析可知，该页面所有链接都在<code>class_=&quot;box pcity&quot;</code>的<code>div</code>块中，是<code>a</code>标签，因此可以通过以下函数来获取所有链接，该函数将所有链接存放在一个列表中并返回。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_href</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    作用：获取所有天气链接</span></span><br><span class="line"><span class="string">    参数：无</span></span><br><span class="line"><span class="string">    返回值：href_list 所有天气链接的列表</span></span><br><span class="line"><span class="string">    使用方式：list = get_href()</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    <span class="comment"># 设置网页链接和head等信息</span></span><br><span class="line">    url = <span class="string">'http://www.tianqihoubao.com/lishi/beijing.html'</span></span><br><span class="line">    head = &#123;<span class="string">'User-Agent'</span>: <span class="string">'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'</span>&#125;</span><br><span class="line">    <span class="comment"># 获取网页文件并分析</span></span><br><span class="line">    html = requests.get(url, headers=head)</span><br><span class="line">    bsObj = BeautifulSoup(html.content, <span class="string">'lxml'</span>)</span><br><span class="line">    <span class="comment"># 找到所有天气链接所在区块</span></span><br><span class="line">    allLinks = bsObj.find_all(<span class="string">'div'</span>, class_=<span class="string">"box pcity"</span>)</span><br><span class="line">    href_list = []</span><br><span class="line">    <span class="comment"># 提取所有链接并存入列表返回</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> allLinks[:<span class="number">10</span>]:</span><br><span class="line">        aLink = i.find_all(<span class="string">'a'</span>)</span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> aLink:</span><br><span class="line">            href = urljoin(url, j[<span class="string">'href'</span>])</span><br><span class="line">            href_list.append(href)</span><br><span class="line">    <span class="keyword">return</span> href_list</span><br></pre></td></tr></table></figure>
</li>
<li><p>得到所有链接的列表后，遍历该列表即可访问每个月的天气数据网页，分析这些网页可以发现，天气数据存放在<code>table</code>中，每一行的标签为<code>tr</code>，每一项的标签为<code>td</code>，而一行有四项，分别是日期、天气、温度、风力风向，其中第一行是表格头，因此可以从表格的第二行（第二个<code>tr</code>）开始遍历，获取所有<code>td</code>的内容（是一个长度为4的列表），将内容逐一处理再存放在列表中。遍历完成后即可得到所有天气数据，我将这些数据存放在列表中并返回，函数如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">analysis_href</span><span class="params">(href_list)</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    作用：分析处理天气链接里的数据</span></span><br><span class="line"><span class="string">    参数：href_list 天气链接列表</span></span><br><span class="line"><span class="string">    返回值：lists 所有处理后的天气数据，格式为[日期、天气、温度、风力风向]</span></span><br><span class="line"><span class="string">    使用方式：lists = analysis_href(href_list)</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    <span class="comment"># 设置head</span></span><br><span class="line">    head = &#123;<span class="string">'User-Agent'</span>: <span class="string">'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'</span>&#125;</span><br><span class="line">    lists = []</span><br><span class="line">    <span class="comment"># 遍历所有链接</span></span><br><span class="line">    <span class="keyword">for</span> href <span class="keyword">in</span> href_list:</span><br><span class="line">        <span class="comment"># 获取网页文件并分析</span></span><br><span class="line">        html = requests.get(href, headers=head)</span><br><span class="line">        bsObj = BeautifulSoup(html.content, <span class="string">'lxml'</span>)</span><br><span class="line">        <span class="comment"># 找到天气数据所在的表格</span></span><br><span class="line">        table = bsObj.find(<span class="string">"table"</span>).find_all(<span class="string">"tr"</span>)</span><br><span class="line">        <span class="comment"># 从表格第二行开始提取数据（第一行是表格的head）</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> table[<span class="number">1</span>:]:</span><br><span class="line">            content = i.find_all(<span class="string">"td"</span>)</span><br><span class="line">            <span class="comment"># 提取日期并去除多余的空格和换行符等</span></span><br><span class="line">            date = content[<span class="number">0</span>].text.replace(</span><br><span class="line">                <span class="string">" "</span>, <span class="string">""</span>).replace(<span class="string">'\n'</span>, <span class="string">''</span>).replace(<span class="string">'\r'</span>, <span class="string">''</span>)</span><br><span class="line">            <span class="comment"># 提取天气并去除多余的空格和换行符等</span></span><br><span class="line">            weather = content[<span class="number">1</span>].text.replace(<span class="string">" "</span>, <span class="string">""</span>).replace(</span><br><span class="line">                <span class="string">" "</span>, <span class="string">""</span>).replace(<span class="string">'\n'</span>, <span class="string">''</span>).replace(<span class="string">'\r'</span>, <span class="string">''</span>)</span><br><span class="line">            <span class="comment"># 提取温度并去除多余的空格和换行符等</span></span><br><span class="line">            temperature = content[<span class="number">2</span>].text.strip().replace(</span><br><span class="line">                <span class="string">" "</span>, <span class="string">""</span>).replace(<span class="string">'\n'</span>, <span class="string">''</span>).replace(<span class="string">'\r'</span>, <span class="string">''</span>)</span><br><span class="line">            <span class="comment"># 提取风力风向并去除多余的空格和换行符等</span></span><br><span class="line">            wind = content[<span class="number">3</span>].text.strip().replace(</span><br><span class="line">                <span class="string">" "</span>, <span class="string">""</span>).replace(<span class="string">'\n'</span>, <span class="string">''</span>).replace(<span class="string">'\r'</span>, <span class="string">''</span>)</span><br><span class="line">            <span class="comment"># 将提取的数据存入列表</span></span><br><span class="line">            lists.append([date, weather, temperature, wind])</span><br><span class="line">    <span class="keyword">return</span> lists</span><br></pre></td></tr></table></figure>
</li>
<li><p>在得到天气数据的列表后，需要将该列表数据写入excel文件，我先将列表转为<code>numpy</code>数组，再将该数组转为<code>DataFrame</code>，并把索引设置为<code>日期</code>列，这时就可以用<code>pandas</code>的库函数将所有内容写入<code>excel</code>文件了，函数如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">write_excel</span><span class="params">(filename)</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    作用：将数据写入excel文件</span></span><br><span class="line"><span class="string">    参数：filename 文件名</span></span><br><span class="line"><span class="string">    返回值：无</span></span><br><span class="line"><span class="string">    使用方式：write_excel("weather.xlsx")</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    <span class="comment"># 调用分析网页的函数获取所有天气数据所在列表</span></span><br><span class="line">    a = np.array(analysis_href(get_href()))</span><br><span class="line">    <span class="comment"># 将天气数据列表转为DateFrame</span></span><br><span class="line">    DF = pd.DataFrame(a, columns=[<span class="string">'日期'</span>, <span class="string">'天气'</span>, <span class="string">'温度'</span>, <span class="string">'风力风向'</span>])</span><br><span class="line">    <span class="comment"># 将索引设置为日期列，去除原本的索引序号</span></span><br><span class="line">    DF.set_index(<span class="string">'日期'</span>, inplace=<span class="literal">True</span>)</span><br><span class="line">    <span class="comment"># 将数据写入excel文件</span></span><br><span class="line">    DF.to_excel(filename)</span><br></pre></td></tr></table></figure>
</li>
<li><p>在主函数中通过调用<code>write_excel()</code>即可得到天气数据文件，完成第一题。</p>
</li>
</ol>
<h3 id="第二题"><a href="#第二题" class="headerlink" title="第二题"></a>第二题</h3><ol>
<li><p>首先读取天气数据和空气质量数据，并将<code>日期</code>列设置为<code>datetime</code>格式的索引，以便后续分析。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 读取数据</span></span><br><span class="line">df_weather = pd.read_excel(<span class="string">'weather.xlsx'</span>, <span class="string">'Sheet1'</span>, header=<span class="number">0</span>)</span><br><span class="line">df_air = pd.read_excel(<span class="string">'北京空气质量.xlsx'</span>, <span class="string">'Sheet1'</span>, header=<span class="number">0</span>)</span><br><span class="line">df_weather[<span class="string">'日期'</span>] = pd.to_datetime(df_weather[<span class="string">'日期'</span>], format=<span class="string">"%Y年%m月%d日"</span>)</span><br><span class="line">df_weather.set_index(<span class="string">'日期'</span>, inplace=<span class="literal">True</span>)</span><br><span class="line">df_air[<span class="string">'日期'</span>] = pd.to_datetime(df_air[<span class="string">'日期'</span>], format=<span class="string">"%Y-%m-%d"</span>)</span><br><span class="line">df_air.set_index(<span class="string">'日期'</span>, inplace=<span class="literal">True</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>接下来通过<code>pandas</code>的库函数即可将两个<code>DataFrame</code>按日期融合起来，因为两个表格中的日期并没有完全一致，所以去除了不一致的日期。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">df_merge = pd.merge(df_weather, df_air, on=<span class="string">'日期'</span>)</span><br><span class="line">df_merge.index = df_merge.index.date</span><br></pre></td></tr></table></figure>
</li>
<li><p>将该<code>DataFrame</code>写入<code>excel</code>文件，完成第二题。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">df_merge.to_excel(<span class="string">'merge.xlsx'</span>)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="第三题"><a href="#第三题" class="headerlink" title="第三题"></a>第三题</h3><ol>
<li><p>分析天气数据，可以看出白天天气和夜晚天气通过<code>/</code>分隔，因此首先通过<code>split()</code>函数得到白天天气。</p>
</li>
<li><p>由于数据源本身的问题，有个别天气是无效的（是<code>-</code>符号），因此要删去这些数据。</p>
</li>
<li><p>得到白天天气后，还需要将该天气转换为题目中提到的几个类别中的一个，例如“小雨”要转换为“雨”。值得注意的是，”雨夹雪“天气我算作雨天而不是雪天。</p>
</li>
<li><p>上述处理天气数据的函数如下，该函数返回处理好的天气数据。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">process_weather_data</span><span class="params">(df_weather)</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    作用：处理天气数据以便后续绘图</span></span><br><span class="line"><span class="string">    参数：df_weather 初始天气数据</span></span><br><span class="line"><span class="string">    返回值：df_weather 处理好的天气数据</span></span><br><span class="line"><span class="string">    使用方式：df_weather = process_weather_data(df_weather)</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    <span class="comment"># 分离出白天天气</span></span><br><span class="line">    df_weather[<span class="string">'白天天气'</span>] = df_weather[<span class="string">'天气'</span>].map(<span class="keyword">lambda</span> x: x.split(<span class="string">'/'</span>)[<span class="number">0</span>])</span><br><span class="line">    <span class="comment"># 删去无效数据</span></span><br><span class="line">    df_weather = df_weather.drop(df_weather[df_weather[<span class="string">'白天天气'</span>] == <span class="string">'-'</span>].index)</span><br><span class="line">    <span class="comment"># 统一雨天数据</span></span><br><span class="line">    df_weather.loc[(df_weather[<span class="string">'白天天气'</span>] == <span class="string">'小雨'</span>) | (df_weather[<span class="string">'白天天气'</span>] == <span class="string">'中雨'</span>) | (df_weather[<span class="string">'白天天气'</span>] == <span class="string">'大雨'</span>) | (df_weather[<span class="string">'白天天气'</span>] == <span class="string">'暴雨'</span>) | (df_weather[<span class="string">'白天天气'</span>] == <span class="string">'阵雨'</span>) | ( df_weather[<span class="string">'白天天气'</span>] == <span class="string">'小到中雨'</span>) | (df_weather[<span class="string">'白天天气'</span>] == <span class="string">'中到大雨'</span>) | (df_weather[<span class="string">'白天天气'</span>] == <span class="string">'雷阵雨'</span>) | (df_weather[<span class="string">'白天天气'</span>] == <span class="string">'雨夹雪'</span>), <span class="string">'白天天气'</span>] = <span class="string">'雨'</span></span><br><span class="line">    <span class="comment"># 统一雪天数据</span></span><br><span class="line">    df_weather.loc[(df_weather[<span class="string">'白天天气'</span>] == <span class="string">'小雪'</span>) | (df_weather[<span class="string">'白天天气'</span>] == <span class="string">'中雪'</span>) | (df_weather[<span class="string">'白天天气'</span>] == <span class="string">'大雪'</span>) | ( df_weather[<span class="string">'白天天气'</span>] == <span class="string">'小到中雪'</span>) | (df_weather[<span class="string">'白天天气'</span>] == <span class="string">'中到大雪'</span>), <span class="string">'白天天气'</span>] = <span class="string">'雪'</span></span><br><span class="line">    <span class="comment"># 统一扬沙天气</span></span><br><span class="line">    df_weather.loc[df_weather[<span class="string">'白天天气'</span>] == <span class="string">'浮尘'</span>, <span class="string">'白天天气'</span>] = <span class="string">'扬沙'</span></span><br><span class="line">    <span class="comment"># 统一雾霾天气</span></span><br><span class="line">    df_weather.loc[(df_weather[<span class="string">'白天天气'</span>] == <span class="string">'雾'</span>) | ( df_weather[<span class="string">'白天天气'</span>] == <span class="string">'霾'</span>), <span class="string">'白天天气'</span>] = <span class="string">'雾霾'</span></span><br><span class="line">    <span class="keyword">return</span> df_weather</span><br></pre></td></tr></table></figure>
</li>
<li><p>对处理好的数据按年分组，再遍历分组结果，可以得到每一年的数据，由于题目要求2011年至2019年，因此当遍历到2020年时终止循环。</p>
</li>
<li><p>对每一年的数据按白天天气这一列分组，统计分组的<code>size</code>，即可得到每种天气的天数，在此基础上可以绘制图像。上述分组并统计绘图的函数如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">weather_pie</span><span class="params">(df_weather)</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    作用：根据处理好的天气数据画饼状图</span></span><br><span class="line"><span class="string">    参数：df_weather 处理好的天气数据</span></span><br><span class="line"><span class="string">    返回值：无</span></span><br><span class="line"><span class="string">    使用方式：weather_pie(df_weather)</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    <span class="comment"># 按年份分组</span></span><br><span class="line">    weather_group_y = df_weather.groupby(df_weather.index.year)</span><br><span class="line">    <span class="comment"># 对每年进行循环</span></span><br><span class="line">    <span class="keyword">for</span> n, g <span class="keyword">in</span> weather_group_y:</span><br><span class="line">        <span class="comment"># 不需要2020的数据</span></span><br><span class="line">        <span class="keyword">if</span> n == <span class="number">2020</span>:</span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">        <span class="comment"># 按白天天气分组</span></span><br><span class="line">        weather_group = g.groupby(g[<span class="string">'白天天气'</span>]).size()</span><br><span class="line">        <span class="comment"># 输出分组结果</span></span><br><span class="line">        print(str(n)+<span class="string">'年天气天数统计如下：'</span>)</span><br><span class="line">        print(weather_group)</span><br><span class="line">        <span class="comment"># 画饼图并保存</span></span><br><span class="line">        weather_group.name = <span class="string">''</span></span><br><span class="line">        weather_group.plot.pie(startangle=<span class="number">90</span>)</span><br><span class="line">        plt.title(<span class="string">''</span>, fontproperties=<span class="string">'Kaiti'</span>)</span><br><span class="line">        plt.savefig(<span class="string">'weather-pie-of-'</span>+str(n), dpi=<span class="number">300</span>)</span><br><span class="line">        plt.show()</span><br></pre></td></tr></table></figure>
</li>
<li><p>在主函数中调用<code>weather_pie()</code>，参数为第二题中读取的天气数据，完成第三题。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">weather_pie(process_weather_data(df_weather))</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="第四题"><a href="#第四题" class="headerlink" title="第四题"></a>第四题</h3><ol>
<li><p>针对每一年的数据，首先根据空气质量等级区分开有污染和无污染，为了方便，我新增一列存储污染情况，将所有无污染的数据设置为0，有污染的设置为1。</p>
</li>
<li><p>同样是数据源的问题，个别数据的空气质量等级是无，属于无效数据，因此我删去这些数据。</p>
</li>
<li><p>接下来统计持续污染天数，这里参考了<a href="https://www.zhihu.com/question/41265794" target="_blank" rel="noopener">知乎</a>。具体方法是首先找到污染情况不同的坐标，该坐标就是持续同一污染状态的终点，而上一次持续的终点也是下一次持续的起点，因此可以得到一个存储了持续污染情况天数的表格，再从该表格中取出污染情况为1的部分，并进行分组统计，即可得到这一年持续<code>n</code>天污染的统计结果。需要注意的是，因为题目要求最高统计5天及以上，这里要把持续天数超过5天的也改为5。</p>
</li>
<li><p>由于这一题并不是每一年画一个图，而是所有数据一起画图，因此这里最后要把得到的统计结果转置，存储为行名是年份、列名是污染持续天数的新<code>DataFrame</code>，并返回。上述处理过程的函数如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">process_air_data</span><span class="params">(df, year)</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    作用：处理空气污染数据</span></span><br><span class="line"><span class="string">    参数：df 初始空气污染数据</span></span><br><span class="line"><span class="string">    返回值：df3 处理好的空气污染数据</span></span><br><span class="line"><span class="string">    使用方式：df_air = process_air_data(df_air)</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    <span class="comment"># 统一污染</span></span><br><span class="line">    df.loc[(df[<span class="string">'质量等级'</span>] == <span class="string">'轻度污染'</span>) | (df[<span class="string">'质量等级'</span>] == <span class="string">'中度污染'</span>) | (</span><br><span class="line">        df[<span class="string">'质量等级'</span>] == <span class="string">'重度污染'</span>) | (df[<span class="string">'质量等级'</span>] == <span class="string">'严重污染'</span>), <span class="string">'污染'</span>] = <span class="number">1</span></span><br><span class="line">    <span class="comment"># 统一无污染</span></span><br><span class="line">    df.loc[(df[<span class="string">'质量等级'</span>] == <span class="string">'优'</span>) | (df[<span class="string">'质量等级'</span>] == <span class="string">'良'</span>), <span class="string">'污染'</span>] = <span class="number">0</span></span><br><span class="line">    <span class="comment"># 删去无效数据</span></span><br><span class="line">    df = df.drop(df[df[<span class="string">'质量等级'</span>] == <span class="string">'无'</span>].index)</span><br><span class="line">    <span class="comment"># 找污染数字相同的位置</span></span><br><span class="line">    pos, = np.where(np.diff(df[<span class="string">'污染'</span>]))</span><br><span class="line">    <span class="comment"># 定位连续污染和连续无污染的起止点</span></span><br><span class="line">    start, end = np.insert(pos+<span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>), np.append(pos, len(df)<span class="number">-1</span>)</span><br><span class="line">    <span class="comment"># 计算污染状态的持续天数</span></span><br><span class="line">    df2 = pd.DataFrame(&#123;<span class="string">'污染'</span>: df[<span class="string">'污染'</span>][start], <span class="string">'持续天数'</span>: end-start+<span class="number">1</span>&#125;)</span><br><span class="line">    <span class="comment"># 从连续天数的表格中提取是污染的</span></span><br><span class="line">    df3 = df2.loc[df2[<span class="string">'污染'</span>] == <span class="number">1</span>]</span><br><span class="line">    <span class="comment"># 连续天数大于5的统一变成5，方便下一步分组统计画图</span></span><br><span class="line">    df3.loc[df3[<span class="string">'持续天数'</span>] &gt; <span class="number">5</span>, <span class="string">'持续天数'</span>] = <span class="number">5</span></span><br><span class="line">    <span class="comment"># 按持续天数分组计数，并将计数结果存为DateFrame</span></span><br><span class="line">    df3 = df3.groupby(df3[<span class="string">'持续天数'</span>]).size().reset_index(name=str(year))</span><br><span class="line">    <span class="comment"># 重置index</span></span><br><span class="line">    df3.set_index(<span class="string">'持续天数'</span>, inplace=<span class="literal">True</span>)</span><br><span class="line">    <span class="comment"># 转置行列，方便后续合并分组结果和画图</span></span><br><span class="line">    df3 = pd.DataFrame(df3.values.T, index=df3.columns, columns=[<span class="string">'1天'</span>, <span class="string">'2天'</span>, <span class="string">'3天'</span>, <span class="string">'4天'</span>, <span class="string">'5天及以上'</span>])</span><br><span class="line">    <span class="keyword">return</span> df3</span><br></pre></td></tr></table></figure>
</li>
<li><p>接下来是画图函数，该函数将合并了所有年份的数据绘制为条形图，如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">pollution_bar</span><span class="params">(df)</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    作用：按处理好的空气污染数据画柱状图</span></span><br><span class="line"><span class="string">    参数：df 处理好的空气污染数据</span></span><br><span class="line"><span class="string">    返回值：无</span></span><br><span class="line"><span class="string">    使用方式：pollution_bar(df_air)</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    df.plot.bar()</span><br><span class="line">    plt.title(<span class="string">'2014年至2019年持续污染天数柱状图'</span>, fontproperties=<span class="string">'Kaiti'</span>)</span><br><span class="line">    plt.xlabel(<span class="string">'天数'</span>, fontproperties=<span class="string">'Kaiti'</span>)</span><br><span class="line">    plt.ylabel(<span class="string">'出现次数'</span>, fontproperties=<span class="string">'Kaiti'</span>)</span><br><span class="line">    plt.tight_layout()</span><br><span class="line">    plt.xticks(rotation=<span class="number">0</span>)</span><br><span class="line">    plt.savefig(<span class="string">'pollution-bar'</span>, dpi=<span class="number">300</span>)</span><br><span class="line">    plt.show()</span><br></pre></td></tr></table></figure>
</li>
<li><p>最后要在主函数中将原始的空气污染数据按年分组，并对分组结果逐一调用<code>process_air_data()</code>，再将得到的持续污染天数的数据合并起来，如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">air_group_y = df_air.groupby(df_air.index.year)</span><br><span class="line">df_air_processed = process_air_data(air_group_y.get_group(<span class="number">2014</span>), <span class="number">2014</span>)</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">2015</span>, <span class="number">2020</span>):</span><br><span class="line">    df_air_processed = pd.concat([df_air_processed, process_air_data(air_group_y.get_group(i), i)])</span><br></pre></td></tr></table></figure>
</li>
<li><p>对处理好的数据调用<code>pollution_bar()</code>绘制条形图，参数是第二题中读取的空气污染数据，完成第四题。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pollution_bar(df_air_processed)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="第五题"><a href="#第五题" class="headerlink" title="第五题"></a>第五题</h3><ol>
<li><p>分析题目要求，”<strong>根据当天的天气情况以及前两天的天气及空气质量情况，预测当天的空气质量等级</strong>“，而天气情况包括天气、温度和风力风向，因此需要进行以下处理。</p>
</li>
<li><p>首先将白天和晚上的天气、风力风向和最高最低温度分离出来，这三个数据都是以<code>/</code>为分隔，因此可以用<code>split()</code>来完成。这里要注意，温度数据的最后一位是摄氏度的标记，因此要去掉，只保留前面的数字。</p>
</li>
<li><p>接下来分离风力和风向，这里的规律并不明显，但总体而言可以用<code>风</code>字作为分隔符来提取，并在之后的处理中将相同含义但不同表示的字符串合并起来。</p>
</li>
<li><p>天气、风力和风向的数据都是字符串，而其它数据则是数字，由于<code>scikit</code>处理的数据都是数字，因此这里需要对字符串进行特征提取和编码，最初我尝试用<code>DictVectorizer</code>来做，但是这样出来的矩阵略大，而结果准确率也略低，因此决定在这里直接用字典和<code>mapping()</code>将字符串转数字。需要注意的是，在这里我把<code>西南偏南</code>和<code>西南</code>算作同一类，用相同的数字表示。另一方面，上一步中分离出的风力数据，如<code>向≤3级</code>、<code>&lt;3级</code>、<code>1-2级</code>等这些显然是同一个含义的也算作一类，用相同的数字表示。</p>
</li>
<li><p>由于天气种类很多，而其中有一些属于同一类，如果不合并相同类别的数据，会对之后的模型训练造成影响，因此按第三题的方法将所有天气统一，并转为数字表示。</p>
</li>
<li><p>质量等级也是字符串，因此采用同样的方法进行转换。转换结束后，原本的天气、风力风向等等数据就可以删除了。</p>
</li>
<li><p>由于预测还用到了前两天的天气和空气质量情况，因此要把前两天的数据逐一增加到当天数据中，作为新的一列保存，之后要删除无效数据。</p>
</li>
<li><p>由于预测时并没有用到当天的空气质量情况，因此要把当天的空气质量数据都删除，只保留空气质量等级这一列作为训练模型的<code>target</code>。</p>
</li>
<li><p>至此，所有数据已经转为数字类型，并剔除不需要的数据，接下来需要进行标准化，并返回标准化之后的数组，该数组第一列是<code>target</code>，剩下数据是训练用数据。上述数据处理过程为如下函数：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">process_predict_data</span><span class="params">(df)</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    作用：处理天气和空气数据，方便后续训练</span></span><br><span class="line"><span class="string">    参数：df 初始合并好的天气+空气数据</span></span><br><span class="line"><span class="string">    返回值：df 处理好的数据</span></span><br><span class="line"><span class="string">    使用方式：predict_array = process_predict_data(df)</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    <span class="comment"># 划分天气、风力、风向和温度</span></span><br><span class="line">    df[<span class="string">'白天天气'</span>] = df[<span class="string">'天气'</span>].map(<span class="keyword">lambda</span> x: x.split(<span class="string">'/'</span>)[<span class="number">0</span>])</span><br><span class="line">    df[<span class="string">'夜晚天气'</span>] = df[<span class="string">'天气'</span>].map(<span class="keyword">lambda</span> x: x.split(<span class="string">'/'</span>)[<span class="number">1</span>])</span><br><span class="line">    df[<span class="string">'白天风力风向'</span>] = df[<span class="string">'风力风向'</span>].map(<span class="keyword">lambda</span> x: x.split(<span class="string">'/'</span>)[<span class="number">0</span>])</span><br><span class="line">    df[<span class="string">'夜晚风力风向'</span>] = df[<span class="string">'风力风向'</span>].map(<span class="keyword">lambda</span> x: x.split(<span class="string">'/'</span>)[<span class="number">1</span>])</span><br><span class="line">    df[<span class="string">'最高温度'</span>] = df[<span class="string">'温度'</span>].map(<span class="keyword">lambda</span> x: int(x.split(<span class="string">'/'</span>)[<span class="number">0</span>][:<span class="number">-1</span>]))</span><br><span class="line">    df[<span class="string">'最低温度'</span>] = df[<span class="string">'温度'</span>].map(<span class="keyword">lambda</span> x: int(x.split(<span class="string">'/'</span>)[<span class="number">1</span>][:<span class="number">-1</span>]))</span><br><span class="line">    df[<span class="string">'白天风力'</span>] = df[<span class="string">'白天风力风向'</span>].map(<span class="keyword">lambda</span> x: x.split(<span class="string">'风'</span>)[<span class="number">0</span>])</span><br><span class="line">    df[<span class="string">'白天风向'</span>] = df[<span class="string">'白天风力风向'</span>].map(<span class="keyword">lambda</span> x: x.split(<span class="string">'风'</span>)[<span class="number">1</span>])</span><br><span class="line">    df[<span class="string">'夜晚风力'</span>] = df[<span class="string">'夜晚风力风向'</span>].map(<span class="keyword">lambda</span> x: x.split(<span class="string">'风'</span>)[<span class="number">0</span>])</span><br><span class="line">    df[<span class="string">'夜晚风向'</span>] = df[<span class="string">'夜晚风力风向'</span>].map(<span class="keyword">lambda</span> x: x.split(<span class="string">'风'</span>)[<span class="number">1</span>])</span><br><span class="line">    <span class="comment"># 风向转数字</span></span><br><span class="line">    wind_map_1 = &#123;<span class="string">'无持续'</span>: <span class="number">0</span>, <span class="string">'东'</span>: <span class="number">1</span>, <span class="string">'南'</span>: <span class="number">2</span>, <span class="string">'西'</span>: <span class="number">3</span>, <span class="string">'北'</span>: <span class="number">4</span>, <span class="string">'东北'</span>: <span class="number">5</span>, <span class="string">'东南'</span>: <span class="number">6</span>, <span class="string">'西北'</span>: <span class="number">7</span>, <span class="string">'西南'</span>: <span class="number">8</span>, <span class="string">'西南偏南'</span>: <span class="number">8</span>&#125;</span><br><span class="line">    df[<span class="string">'白天风力'</span>] = df[<span class="string">'白天风力'</span>].map(wind_map_1)</span><br><span class="line">    df[<span class="string">'夜晚风力'</span>] = df[<span class="string">'夜晚风力'</span>].map(wind_map_1)</span><br><span class="line">    <span class="comment"># 风力转数字</span></span><br><span class="line">    wind_map_2 = &#123;<span class="string">'向≤3级'</span>: <span class="number">0</span>, <span class="string">'&lt;3级'</span>: <span class="number">0</span>, <span class="string">'1-2级'</span>: <span class="number">0</span>, <span class="string">'≤3级'</span>: <span class="number">0</span>, <span class="string">'向&lt;3级'</span>: <span class="number">0</span>, <span class="string">'向3-4级'</span>: <span class="number">1</span>, <span class="string">'3-4级'</span>: <span class="number">1</span>, <span class="string">'3～4级'</span>: <span class="number">1</span>, <span class="string">'3～4级'</span>: <span class="number">1</span>, <span class="string">'4'</span>: <span class="number">1</span>, <span class="string">'4-5级'</span>: <span class="number">1</span>, <span class="string">'4～5级'</span>: <span class="number">1</span>, <span class="string">'5～6级'</span>: <span class="number">2</span>, <span class="string">'5-6级'</span>: <span class="number">2</span>, <span class="string">'6-7级'</span>: <span class="number">2</span>&#125;</span><br><span class="line">    df[<span class="string">'白天风向'</span>] = df[<span class="string">'白天风向'</span>].map(wind_map_2)</span><br><span class="line">    df[<span class="string">'夜晚风向'</span>] = df[<span class="string">'夜晚风向'</span>].map(wind_map_2)</span><br><span class="line">    <span class="comment"># 删去不需要的列</span></span><br><span class="line">    df = df.drop(<span class="string">'天气'</span>, axis=<span class="number">1</span>).drop(<span class="string">'温度'</span>, axis=<span class="number">1</span>).drop(<span class="string">'风力风向'</span>, axis=<span class="number">1</span>).drop(<span class="string">'白天风力风向'</span>, axis=<span class="number">1</span>).drop(<span class="string">'夜晚风力风向'</span>, axis=<span class="number">1</span>)</span><br><span class="line">    <span class="comment"># 删去无效数据</span></span><br><span class="line">    df = df.drop(df[df[<span class="string">'质量等级'</span>] == <span class="string">'无'</span>].index)</span><br><span class="line">    <span class="comment"># 统一雨天数据</span></span><br><span class="line">    df.loc[(df[<span class="string">'白天天气'</span>] == <span class="string">'小雨'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'中雨'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'大雨'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'暴雨'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'阵雨'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'小到中雨'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'中到大雨'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'雷阵雨'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'雨夹雪'</span>), <span class="string">'白天天气'</span>] = <span class="string">'雨'</span></span><br><span class="line">    df.loc[(df[<span class="string">'夜晚天气'</span>] == <span class="string">'小雨'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'中雨'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'大雨'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'暴雨'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'阵雨'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'小到中雨'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'中到大雨'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'大到暴雨'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'雷阵雨'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'雨夹雪'</span>), <span class="string">'夜晚天气'</span>] = <span class="string">'雨'</span></span><br><span class="line">    <span class="comment"># 统一雪天数据</span></span><br><span class="line">    df.loc[(df[<span class="string">'白天天气'</span>] == <span class="string">'小雪'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'中雪'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'大雪'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'小到中雪'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'中到大雪'</span>), <span class="string">'白天天气'</span>] = <span class="string">'雪'</span></span><br><span class="line">    df.loc[(df[<span class="string">'夜晚天气'</span>] == <span class="string">'小雪'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'中雪'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'大雪'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'小到中雪'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'中到大雪'</span>), <span class="string">'夜晚天气'</span>] = <span class="string">'雪'</span></span><br><span class="line">    <span class="comment"># 统一扬沙天气</span></span><br><span class="line">    df.loc[df[<span class="string">'白天天气'</span>] == <span class="string">'浮尘'</span>, <span class="string">'白天天气'</span>] = <span class="string">'扬沙'</span></span><br><span class="line">    df.loc[df[<span class="string">'夜晚天气'</span>] == <span class="string">'浮尘'</span>, <span class="string">'夜晚天气'</span>] = <span class="string">'扬沙'</span></span><br><span class="line">    <span class="comment"># 统一雾霾天气</span></span><br><span class="line">    df.loc[(df[<span class="string">'白天天气'</span>] == <span class="string">'雾'</span>) | (df[<span class="string">'白天天气'</span>] == <span class="string">'霾'</span>), <span class="string">'白天天气'</span>] = <span class="string">'雾霾'</span></span><br><span class="line">    df.loc[(df[<span class="string">'夜晚天气'</span>] == <span class="string">'雾'</span>) | (df[<span class="string">'夜晚天气'</span>] == <span class="string">'霾'</span>), <span class="string">'夜晚天气'</span>] = <span class="string">'雾霾'</span></span><br><span class="line">    <span class="comment"># 质量等级转数字</span></span><br><span class="line">    quality_mapping = &#123;<span class="string">'优'</span>: <span class="number">0</span>, <span class="string">'良'</span>: <span class="number">1</span>, <span class="string">'轻度污染'</span>: <span class="number">2</span>, <span class="string">'中度污染'</span>: <span class="number">3</span>, <span class="string">'重度污染'</span>: <span class="number">4</span>, <span class="string">'严重污染'</span>: <span class="number">5</span>&#125;</span><br><span class="line">    df[<span class="string">'质量等级'</span>] = df[<span class="string">'质量等级'</span>].map(quality_mapping)</span><br><span class="line">    <span class="comment"># 天气转数字</span></span><br><span class="line">    weather_mapping = &#123;<span class="string">'晴'</span>: <span class="number">0</span>, <span class="string">'雨'</span>: <span class="number">1</span>, <span class="string">'阴'</span>: <span class="number">2</span>, <span class="string">'雪'</span>: <span class="number">3</span>, <span class="string">'多云'</span>: <span class="number">4</span>, <span class="string">'雾霾'</span>: <span class="number">5</span>, <span class="string">'扬沙'</span>: <span class="number">6</span>&#125;</span><br><span class="line">    df[<span class="string">'白天天气'</span>] = df[<span class="string">'白天天气'</span>].map(weather_mapping)</span><br><span class="line">    df[<span class="string">'夜晚天气'</span>] = df[<span class="string">'夜晚天气'</span>].map(weather_mapping)</span><br><span class="line">    <span class="comment"># 增加昨天和前天的数据</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(len(df)<span class="number">-2</span>):</span><br><span class="line">        df.ix[i+<span class="number">2</span>, <span class="string">'昨天AQI'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天质量等级'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天PM2.5'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天PM10'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天SO2'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天CO'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天NO2'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天O3_8h'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天白天天气'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天夜晚天气'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天白天风力'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天夜晚风力'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天白天风向'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天夜晚风向'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天最高温度'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'昨天最低温度'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天AQI'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天质量等级'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天PM2.5'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天PM10'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天SO2'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天CO'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天NO2'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天O3_8h'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天白天天气'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天夜晚天气'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天白天风力'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天夜晚风力'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天白天风向'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天夜晚风向'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天最高温度'</span>], df.ix[i+<span class="number">2</span>, <span class="string">'前天最低温度'</span>] = df.ix[i+<span class="number">1</span>, <span class="string">'AQI'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'质量等级'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'PM2.5'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'PM10'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'SO2'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'CO'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'NO2'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'O3_8h'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'白天天气'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'夜晚天气'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'白天风力'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'夜晚风力'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'白天风向'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'夜晚风向'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'最高温度'</span>], df.ix[i+<span class="number">1</span>, <span class="string">'最低温度'</span>], df.ix[i, <span class="string">'AQI'</span>], df.ix[i, <span class="string">'质量等级'</span>], df.ix[i, <span class="string">'PM2.5'</span>], df.ix[i, <span class="string">'PM10'</span>], df.ix[i, <span class="string">'SO2'</span>], df.ix[i, <span class="string">'CO'</span>], df.ix[i, <span class="string">'NO2'</span>], df.ix[i, <span class="string">'O3_8h'</span>], df.ix[i, <span class="string">'白天天气'</span>], df.ix[i, <span class="string">'夜晚天气'</span>], df.ix[i, <span class="string">'白天风力'</span>], df.ix[i, <span class="string">'夜晚风力'</span>], df.ix[i, <span class="string">'白天风向'</span>], df.ix[i, <span class="string">'夜晚风向'</span>], df.ix[i, <span class="string">'最高温度'</span>], df.ix[i, <span class="string">'最低温度'</span>]</span><br><span class="line">    <span class="comment"># 删除无效数据</span></span><br><span class="line">    df = df.dropna(how=<span class="string">'any'</span>)</span><br><span class="line">    <span class="comment"># 删除今天空气数据</span></span><br><span class="line">    df = df.drop(<span class="string">'AQI'</span>, axis=<span class="number">1</span>).drop(<span class="string">'PM2.5'</span>, axis=<span class="number">1</span>).drop(<span class="string">'PM10'</span>, axis=<span class="number">1</span>).drop(</span><br><span class="line">        <span class="string">'SO2'</span>, axis=<span class="number">1</span>).drop(<span class="string">'CO'</span>, axis=<span class="number">1</span>).drop(<span class="string">'NO2'</span>, axis=<span class="number">1</span>).drop(<span class="string">'O3_8h'</span>, axis=<span class="number">1</span>)</span><br><span class="line">    <span class="comment"># 数据标准化</span></span><br><span class="line">    ss = StandardScaler()</span><br><span class="line">    predict_array = ss.fit_transform(df)</span><br><span class="line">    <span class="keyword">return</span> predict_array</span><br></pre></td></tr></table></figure>
</li>
<li><p>处理好数据后，就可以开始训练模型。首先用<code>train_test_split()</code>划分训练集和测试集。</p>
</li>
<li><p>接下来建立一个算法列表，该列表包含了几个不同的分类器。</p>
</li>
<li><p>对每一个分类器，用K折交叉判断其在训练集的准确率并输出。</p>
</li>
<li><p>根据输出结果选择最优分类器，测试其在测试集上的性能并输出。</p>
</li>
<li><p>在这里经过对比，选择了LDA分类器。整体训练过程如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">predict_air</span><span class="params">(array)</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    作用：训练和测试模型</span></span><br><span class="line"><span class="string">    参数：array 处理好的数据集</span></span><br><span class="line"><span class="string">    返回值：无</span></span><br><span class="line"><span class="string">    使用方式：predict_air(array)</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    <span class="comment"># 划分训练集和测试集</span></span><br><span class="line">    x = array[:, <span class="number">1</span>:]</span><br><span class="line">    y = array[:, <span class="number">0</span>]</span><br><span class="line">    x_train, x_test, y_train, y_test = train_test_split(</span><br><span class="line">        x, y, test_size=<span class="number">0.7</span>, random_state=<span class="number">1</span>)</span><br><span class="line">    <span class="comment"># 把备选算法放入列表</span></span><br><span class="line">    models = []</span><br><span class="line">    models.append((<span class="string">'LR'</span>, LogisticRegression(</span><br><span class="line">        solver=<span class="string">'liblinear'</span>, multi_class=<span class="string">'ovr'</span>)))</span><br><span class="line">    models.append((<span class="string">'LDA'</span>, LinearDiscriminantAnalysis()))</span><br><span class="line">    models.append((<span class="string">'KNN'</span>, KNeighborsClassifier()))</span><br><span class="line">    models.append((<span class="string">'CART'</span>, DecisionTreeClassifier()))</span><br><span class="line">    models.append((<span class="string">'NB'</span>, GaussianNB()))</span><br><span class="line">    models.append((<span class="string">'SVM'</span>, SVC(gamma=<span class="string">'auto'</span>)))</span><br><span class="line">    <span class="comment"># 用训练集训练每个模型并评价</span></span><br><span class="line">    results = []</span><br><span class="line">    names = []</span><br><span class="line">    <span class="keyword">for</span> name, model <span class="keyword">in</span> models:</span><br><span class="line">        kfold = StratifiedKFold(n_splits=<span class="number">10</span>, random_state=<span class="number">1</span>, shuffle=<span class="literal">True</span>)</span><br><span class="line">        cv_results = cross_val_score(model, x_train, y_train.astype(</span><br><span class="line">            <span class="string">'int'</span>), cv=kfold, scoring=<span class="string">'accuracy'</span>)</span><br><span class="line">        results.append(cv_results)</span><br><span class="line">        names.append(name)</span><br><span class="line">        print(<span class="string">'%s: %f (%f)'</span> % (name, cv_results.mean(), cv_results.std()))</span><br><span class="line">    <span class="comment"># 从上面的输出可知lda准确率最高，因此训练lad模型并输出测试集的准确率</span></span><br><span class="line">    lda = LinearDiscriminantAnalysis()</span><br><span class="line">    lda.fit(x_train, y_train.astype(<span class="string">'int'</span>))</span><br><span class="line">    print(lda.score(x_test, y_test.astype(<span class="string">'int'</span>)))</span><br></pre></td></tr></table></figure>
</li>
<li><p>在主函数中先后调用<code>process_predict_data()</code>和<code>predict_air()</code>，在已知某天天气情况和前两天的天气及空气情况时，也可以调用该模型来预测当天空气质量。完成第五题。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">predict = process_predict_data(df_merge)</span><br><span class="line">predict_air(predict)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>好了我终于写完了，这个空气质量预测根本就靠不住，一开始只有准确率只有0.3，用很麻烦的方法处理数据之后才达到现在的0.7。啊写实验报告好累，我总算不用再上课了。希望分数能好点。</p>

      
    </div>
    
    
    

    

    

    
	
	<div>
		
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
		
	</div>
	
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"><i class="fa fa-tag"></i> python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/06/06/vscode%E7%9A%84%E4%B8%80%E7%B3%BB%E5%88%97%E9%85%8D%E7%BD%AE/" rel="next" title="vscode的一系列配置">
                <i class="fa fa-chevron-left"></i> vscode的一系列配置
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/07/05/%E8%AE%BA%E6%96%87%E8%AE%B0%E5%BD%95-%E9%87%8D%E6%9E%84%E6%AF%94%E7%89%B9%E5%B8%81%E8%B4%B9%E7%8E%87%E5%B8%82%E5%9C%BA/" rel="prev" title="论文记录-重构比特币费率市场">
                论文记录-重构比特币费率市场 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/header.jpg"
                alt="Kun Li" />
            
              <p class="site-author-name" itemprop="name">Kun Li</p>
              <p class="site-description motion-element" itemprop="description">三月樱，六月雪，也望尘莫及</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
				<a href="/archives/">
              
                  <span class="site-state-item-count">54</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">27</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/likun1208" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="likun@mail.bnu.edu.cn" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#null"><span class="nav-number">1.</span> <span class="nav-text">北京师范大学2019～2020学年第二学期期末大作业</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#null"><span class="nav-number">2.</span> <span class="nav-text">（研究生）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#题目："><span class="nav-number">2.1.</span> <span class="nav-text">题目：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#承诺："><span class="nav-number">2.2.</span> <span class="nav-text">承诺：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#导入库"><span class="nav-number">2.2.1.</span> <span class="nav-text">导入库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#第一题"><span class="nav-number">2.2.2.</span> <span class="nav-text">第一题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#第二题"><span class="nav-number">2.2.3.</span> <span class="nav-text">第二题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#第三题"><span class="nav-number">2.2.4.</span> <span class="nav-text">第三题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#第四题"><span class="nav-number">2.2.5.</span> <span class="nav-text">第四题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#第五题"><span class="nav-number">2.2.6.</span> <span class="nav-text">第五题</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Kun Li</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  
  <script>
    $('.highlight').each(function (i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap')
      $(e).after($wrap)
      $wrap.append($('<button>').addClass('copy-btn').append('Copy').on('click', function (e) {
        var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
          return $(e).text()
        }).toArray().join('\n')
        var ta = document.createElement('textarea')
        document.body.appendChild(ta)
        ta.style.position = 'absolute'
        ta.style.top = '0px'
        ta.style.left = '0px'
        ta.value = code
        ta.select()
        ta.focus()
        var result = document.execCommand('copy')
        document.body.removeChild(ta)
        
          if(result)$(this).text('Success')
          else $(this).text('Fail')
        
        $(this).blur()
      })).on('mouseleave', function (e) {
        var $b = $(this).find('.copy-btn')
        setTimeout(function () {
          $b.text('Copy')
        }, 300)
      }).append(e)
    })
  </script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"model":{"jsonPath":"/live2dw/assets/z16.model.json"},"display":{"position":"left","width":175,"height":350},"mobile":{"show":false},"log":false});</script></body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
